﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kangsuce.BLL;
using kangsuce.Model;
using Newtonsoft.Json;

namespace kangsuce.Admin.Controllers
{
    public class AccountController : BaseController
    {
        private SysUserBLL sysUserBLL = new SysUserBLL();
        private RoleBLL roleBLL = new RoleBLL();
        private RolePermissionBLL rolePermissionBLL = new RolePermissionBLL();
        private UserRoleBLL userRoleBLL = new UserRoleBLL();
        private WxUserBLL wxUserBLL = new WxUserBLL();

        #region 角色

        /// <summary>
        /// 角色列表
        /// </summary>
        /// <returns></returns>
        public ActionResult RoleList()
        {
            return View();
        }

        /// <summary>
        /// 获取角色列表数据
        /// </summary>
        /// <param name="pageSize">分页大小</param>
        /// <param name="pageNumber">页码</param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult GetRoleList(int pageSize, int pageNumber, string name = "")
        {
            try
            {
                int total;
                var list = roleBLL.GetListByPage(pageSize, pageNumber, out total,
                    p => name == "" || (p.roleName.Contains(name)),
                    orderBy: c => c.OrderBy(p => p.roleId));
                return Json(new {rows = list, total = total}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 角色编辑
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        public ActionResult RoleEdit(int id = 0)
        {
            KSC_Role model = roleBLL.GetModelById(id) ?? new KSC_Role {roleId = 0};
            ViewBag.Json = JsonConvert.SerializeObject(model);
            return View();
        }

        /// <summary>
        /// 角色保存
        /// </summary>
        /// <returns></returns>
        public ActionResult RoleSave()
        {
            try
            {
                int roleId = Convert.ToInt32(Request.Form["roleId"] ?? "0");
                string roleName = System.Web.HttpUtility.UrlDecode(Request.Form["roleName"] ?? "");
                if (roleId == 0)
                {
                    if (roleBLL.GetModel(p => p.roleName == roleName) != null)
                    {
                        return Json(new {result = "error", msg = "角色名重复，请重新输入"});
                    }
                    KSC_Role model = new KSC_Role
                    {
                        createDate = DateTime.Now,
                        roleDisplay = "1",
                        roleName = roleName
                    };
                    roleId = roleBLL.Insert(model);
                    return Json(new {result = roleId > 0 ? "success" : "error", msg = roleId > 0 ? "新增成功" : "新增失败"});
                }
                else
                {
                    KSC_Role model = roleBLL.GetModelById(roleId);
                    if (roleBLL.GetModel(p => p.roleName == roleName && roleName != model.roleName) != null)
                    {
                        return Json(new {result = "error", msg = "角色名重复，请重新输入"});
                    }
                    model.roleName = roleName;
                    bool result = roleBLL.Update(model);
                    return Json(new {result = result ? "success" : "error", msg = result ? "修改成功" : "修改失败"});
                }
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message});
            }
        }

        /// <summary>
        /// 显示/隐藏角色
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RoleChangeDisplay(int id = 0)
        {
            try
            {
                if (id == 0)
                {
                    return Json(new {result = "error", msg = "传入参数有误"}, JsonRequestBehavior.AllowGet);
                }
                KSC_Role model = roleBLL.GetModelById(id);
                model.roleDisplay = model.roleDisplay == "1" ? "0" : "1";
                bool result = roleBLL.Update(model);
                return Json(new {result = result ? "success" : "error", msg = result ? "操作成功" : "操作失败"},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 角色删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult RoleDelete(int id = 0)
        {
            try
            {
                if (id == 0)
                {
                    return Json(new {result = "error", msg = "传入参数有误"}, JsonRequestBehavior.AllowGet);
                }
                bool result = roleBLL.Delete(id);
                if (result)
                {
                    rolePermissionBLL.DeleteByFilter(p => p.roleId == id);
                }
                return Json(new {result = result ? "success" : "error", msg = result ? "删除成功" : "删除失败"},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region 管理员

        /// <summary>
        /// 管理员列表
        /// </summary>
        /// <returns></returns>
        public ActionResult SysUserList()
        {
            return View();
        }

        /// <summary>
        /// 获取管理员列表
        /// </summary>
        /// <param name="pageSize">分页大小</param>
        /// <param name="pageNumber">页码</param>
        /// <param name="name">用户名或登录名</param>
        /// <returns></returns>
        public ActionResult GetSysUserList(int pageSize, int pageNumber, string name = "")
        {
            try
            {
                int total;
                var list = sysUserBLL.GetListByPage(pageSize, pageNumber, out total,
                    p => name == "" || (p.loginName.Contains(name) || p.userName.Contains(name)),
                    c => c.OrderBy(p => p.userId));
                return Json(new {rows = list, total = total}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 管理员编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult SysUserEdit(int id = 0)
        {
            KSC_SysUser model = sysUserBLL.GetModelById(id) ?? new KSC_SysUser {userId = 0};
            ViewBag.Json = JsonConvert.SerializeObject(model);
            return View();
        }

        /// <summary>
        /// 管理员信息保存
        /// </summary>
        /// <returns></returns>
        public ActionResult SysUserSave()
        {
            try
            {
                int userId = Convert.ToInt32(Request.Form["userId"] ?? "0");
                string loginName = System.Web.HttpUtility.UrlDecode(Request.Form["loginName"] ?? ""); //登录名
                string userName = System.Web.HttpUtility.UrlDecode(Request.Form["userName"] ?? ""); //用户名
                string passWord = System.Web.HttpUtility.UrlDecode(Request.Form["passWord"] ?? ""); //密码
                int userType = Convert.ToInt32(Request.Form["userType"] ?? "0"); //用户类别
                if (userId == 0)
                {
                    if (sysUserBLL.GetModel(p => p.loginName == loginName) != null)
                    {
                        return Json(new {result = "error", msg = "登录名重复，请重新输入"});
                    }
                    KSC_SysUser model = new KSC_SysUser
                    {
                        createDate = DateTime.Now,
                        isDisable = "0",
                        loginName = loginName,
                        passWord = passWord,
                        userName = userName,
                        userType = userType
                    };
                    userId = sysUserBLL.Insert(model);
                    return Json(new {result = userId > 0 ? "success" : "error", msg = userId > 0 ? "新增成功" : "新增失败"});
                }
                else
                {
                    KSC_SysUser model = sysUserBLL.GetModelById(userId);
                    if (sysUserBLL.GetModel(p => p.loginName == loginName && model.loginName != loginName) != null)
                    {
                        return Json(new {result = "error", msg = "登录名重复，请重新输入"});
                    }
                    model.userName = userName;
                    model.loginName = loginName;
                    model.userType = userType;
                    bool result = sysUserBLL.Update(model);
                    return Json(new {result = result ? "success" : "error", msg = result ? "修改成功" : "修改失败"});
                }
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message});
            }
        }

        /// <summary>
        /// 禁用/启用管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SysUserChangeDisable(int id = 0)
        {
            try
            {
                if (id == 0)
                {
                    return Json(new {result = "error", msg = "传入参数有误"}, JsonRequestBehavior.AllowGet);
                }
                KSC_SysUser model = sysUserBLL.GetModelById(id);
                model.isDisable = model.isDisable == "1" ? "0" : "1";
                bool result = sysUserBLL.Update(model);
                return Json(new {result = result ? "success" : "error", msg = result ? "操作成功" : "操作失败"},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 管理员删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult SysUserDelete(int id = 0)
        {
            try
            {
                if (id == 0)
                {
                    return Json(new {result = "error", msg = "传入参数有误"}, JsonRequestBehavior.AllowGet);
                }
                bool result = sysUserBLL.Delete(id);
                return Json(new {result = result ? "success" : "error", msg = result ? "删除成功" : "删除失败"},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 管理员角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ActionResult SysUserRoleSet(int userId)
        {
            var list = roleBLL.GetList(p => p.roleDisplay == "1");
            var userRoleList = userRoleBLL.GetList(p => p.userId == userId);
            foreach (KSC_Role item in list.Where(item => !userRoleList.Select(p => p.roleId).Contains(item.roleId)))
            {
                item.roleDisplay = "0";
            }
            ViewBag.List = list;
            return View();
        }

        /// <summary>
        /// 管理员角色保存
        /// </summary>
        /// <param name="userId">管理员id</param>
        /// <param name="roleIds">角色id集合</param>
        /// <returns></returns>
        public ActionResult SysUserRoleSave(int userId = 0, string roleIds = "")
        {
            try
            {
                userRoleBLL.Delete(p => p.userId == userId);
                if (roleIds != "")
                {
                    List<KSC_UserRole> list =
                        roleIds.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries)
                            .Select(roleId => new KSC_UserRole
                            {
                                userId = userId,
                                roleId = Convert.ToInt32(roleId)
                            }).ToList();
                    bool result = userRoleBLL.Insert(list);
                    return Json(new {result = result ? "success" : "error", msg = result ? "保存成功" : "保存失败"});
                }
                return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region 微信用户

        /// <summary>
        /// 微信用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult WxUserList()
        {
            return View();
        }

        /// <summary>
        /// 获取微信用户列表
        /// </summary>
        /// <param name="pageSize">分页大小</param>
        /// <param name="pageNumber">页码</param>
        /// <param name="name">微信昵称</param>
        /// <returns></returns>
        public ActionResult GetWxUserList(int pageSize, int pageNumber, string name = "")
        {
            try
            {
                int total;
                var list = wxUserBLL.GetListByPage(pageSize, pageNumber, out total,
                    p => name == "" || p.nickName.Contains(name), c => c.OrderBy(p => p.userId));
                return Json(new {rows = list, total = total}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion
    }
}